import { ipcMain, desktopCapturer, webContents, BrowserWindow,dialog } from 'electron'
import { readConfig, writeConfig, readFile, readTodoList, writeTodoList, readBookConfig, writeBookConfig, getSection,readMusicConfig,writeMusicConfig } from './utils.js'
import { setModes, updateContextMenu } from './tray.js'
import { showsettingWin } from './setting.js'
import * as mainWin from './mainWin.js';
import { showaboutWin } from './aboutWin.js'
import * as onlineBook from './onlineBook.js'
import * as potato from './potato.js'
import fs from 'fs';
import * as chatWin from './chatWin.js'
import * as jingWin from './jingWin.js'
import * as fiveWin from './fiveWin.js'
import * as notesWin from './notesWin.js'
import * as playerWin from './playerWin.js'
import { getNotesList } from './notes.js'



export const addIpcMain = () => {
    // 设置配置
    ipcMain.on('setConfig', (event, arg) => {
        let config = JSON.parse(arg)
        config.total = Math.ceil(readFile(config.url).length / config.pageSize)
        writeConfig(config)
        mainWin.goHomeMainWin()
    })
    // 获取配置
    ipcMain.on('getConfig', (event, arg) => {
        let config = readConfig()
        if (config == null) {
            event.reply('config', '无')
        } else {
            event.reply('config', JSON.stringify(config))
        }
    })
    // 更新托盘图标状态
    ipcMain.on('updateContextMenu', (event, arg) => {
        setModes({ checkLabel: arg.replace('/', '') })
        updateContextMenu()
    })
    ipcMain.on('showSetting', (event, arg) => {
        showsettingWin()
    })
    ipcMain.on('showAbout', (event, arg) => {
        showaboutWin()
    })
    // 获取todoList
    ipcMain.on('getTodo', (event, arg) => {
        let todoList = readTodoList()
        if (todoList == null) {
            event.reply('todo', '无')
        } else {
            event.reply('todo', JSON.stringify(todoList))
        }
    })
    // 设置todoList
    ipcMain.on('setTodo', (event, arg) => {
        let todoList = JSON.parse(arg)
        writeTodoList(todoList)
    })
    // 获取书籍列表
    ipcMain.on('getBooks', (event, arg) => {
        let bookConfig = readBookConfig()
        if (bookConfig == null) {
            let config = {
                booksList: [],
                lastRead: null,
                userSetting: {
                    color: '#333',
                    background: 'none',
                    border: '1px solid #333',
                    fontSize: '16px'
                }
            }
            writeBookConfig(config)
            event.reply('books', JSON.stringify(config))

        } else {
            event.reply('books', JSON.stringify(bookConfig))
        }
    })
    // 设置书籍列表
    ipcMain.on('setBooks', (event, arg) => {
        let bookConfig = JSON.parse(arg)
        writeBookConfig(bookConfig)
        event.reply('updated', JSON.stringify(bookConfig))
    })
    // 记录当前位置和大小
    ipcMain.on('remenber', (event, arg) => {
        let Bounds = mainWin.getPositionAndSize()
        event.reply('returnRemenber', JSON.stringify(Bounds))
    })
    // 获取章节内容
    ipcMain.on('getSection', async (event, arg) => {
        let bookConfig = readBookConfig()
        if (bookConfig == null) {
            event.reply('section', '无')
        } else {
            if (bookConfig.lastRead == null) {
                event.reply('section', '无')
            } else {
                if (bookConfig.lastRead.type === 'offline') {
                    let file = readFile(bookConfig.lastRead.localUrl)
                    if (file) {
                        let section = getSection(file, bookConfig.lastRead.current)
                        if (bookConfig.lastRead.total == 0) {
                            bookConfig.lastRead.total = section ? section.total : 0
                        }
                        event.reply('section', section ? JSON.stringify(section) : '无')
                    }
                } else if (bookConfig.lastRead.type === 'online') {
                    let section = await onlineBook.getSection(bookConfig.lastRead.webUrl, bookConfig.lastRead.current)
                    if (bookConfig.lastRead.total == 0) {
                        bookConfig.lastRead.total = section ? section.total : 0
                    }
                    event.reply('section', section ? JSON.stringify(section) : '无')
                }
            }

        }
    })
    // 切换到记忆模式
    ipcMain.on('rememberType', (event, arg) => {
        mainWin.rememberType()
    })
    // 搜索书籍
    ipcMain.on('searchBook', async (event, arg) => {
        let res = await onlineBook.searchTxt(arg)
        // let res = await potato.searchTxt(arg)
        event.reply('returnSearchResult', JSON.stringify(res))
    })
    // 获取颜色了，设置全屏蒙版
    ipcMain.on('getColor', (event, arg) => {
        mainWin.fullScrreenMainWin()
    })
    // 取色完成
    ipcMain.on('completeGetColor', (event, arg) => {
        mainWin.exitFullScrreenMainWin()
    })
    // 获取窗口
    ipcMain.handle('getDesktopCapturerSource', async (event) => {
        return [
            ...(await desktopCapturer.getSources({ types: ["window", "screen"] })),
            ...(await selfWindws()),
        ];
    });
    // 获取当前窗口
    const selfWindws = async () => {
        return Promise.all(
            webContents
                .getAllWebContents()
                .filter((item) => {
                    const win = BrowserWindow.fromWebContents(item);
                    return win && win.isVisible();
                })
                .map(async (item) => {
                    const win = BrowserWindow.fromWebContents(item);
                    const thumbnail = await win?.capturePage();
                    // 当程序窗口打开DevTool的时候  也会计入
                    return {
                        name:
                            win?.getTitle() + (item.devToolsWebContents === null ? "" : "-dev"), // 给dev窗口加上后缀
                        id: win?.getMediaSourceId(),
                        thumbnail,
                        display_id: "",
                        appIcon: null,
                    };
                })
        );
    }
    // 保存截图
    ipcMain.on('saveScreenShot', async (event, arg) => {
        const options = {
            title: '保存截图',
            defaultPath: 'screenshot',
            buttonLabel: '保存',
            filters: [{ name: 'PNG', extensions: ['png'] }, { name: 'All Files', extensions: ['*'] }],
        }
        dialog.showSaveDialog(null, options).then((result) => {
            if (result.filePath) {
                try {
                    const base64Data = arg.split(';base64,').pop();
                    fs.writeFileSync(result.filePath, base64Data, 'base64')
                } catch (err) {
                    console.error('save screen shot error:', err);
                }
            }
        })
    })
    // 打开新窗口
    ipcMain.on('openWindow', async (event, arg) => {
        if(arg ==='chat'){
            chatWin.openchatWin()
            chatWin.showchatWin()
        }
        if(arg ==='jing'){
            jingWin.openjingWin()
            jingWin.showjingWin()
        }
        if(arg ==='five'){
            fiveWin.openfiveWin()
            fiveWin.showfiveWin()
        }
        if(arg ==='notes'){
            notesWin.closenotesWin()
            notesWin.opennotesWin()
            notesWin.shownotesWin()
        }
    })
    // 获取笔记列表
    ipcMain.on('getNotesList', async (event, arg) => {
        let notesList = getNotesList()
        event.reply('returnNotesList', JSON.stringify(notesList))
    })
    // 读取图片切换大窗口
    ipcMain.on('measureOpen', async (event, arg) => {
        mainWin.setLargeWin()
    })
    // 退出 返回正常小窗
    ipcMain.on('measureClose', async (event, arg) => {
        mainWin.setNormalWin()
    })
    // 全屏
    ipcMain.on('measureFullScreen', async (event, arg) => {
        mainWin.toggleFullScreen()
    })
    // 准备录制，切换窗口大小
    ipcMain.on('readyRecord', async (event, arg) => {
        mainWin.setRecordWin()
        event.reply('letsfkingRecord', JSON.stringify({}))
    })
    // 录制完成，切换窗口大小
    ipcMain.on('finishRecord', async (event, arg) => {
        mainWin.setNormalWin()
    })
    // 打开播放器窗口
    ipcMain.on('openPlayer', async (event, arg) => {
        playerWin.openplayerWin()
        playerWin.showplayerWin()
    })
    // 获取音乐歌单配置
    ipcMain.on('getMusic', async (event, arg) => {
        let musicList = readMusicConfig()
        event.reply('returnMusic', JSON.stringify(musicList))
    })
    // 写入歌单配置
    ipcMain.on('updateMusic', async (event, arg) => {
        let musicList = JSON.parse(arg)
        writeMusicConfig(musicList)
    })
    // 关闭播放器
    ipcMain.on('closeMusicPlayer', async (event, arg) => {
        playerWin.closeplayerWin()
    })
    // 展开列表
    ipcMain.on('openList', async (event, arg) => {
        playerWin.setListShow()
    })
    // 收起列表
    ipcMain.on('closeList', async (event, arg) => {
        playerWin.setListHide()
    })
}